<?php
namespace App\Model;
use Core\Component\Di;

class FriendRelation{
    protected $lock = false;
    protected $db;
    protected $tableName = 'friend_relation';

    function __construct(){
        $db = Di::getInstance()->get("MYSQL");
        if($db instanceof \MysqliDb){
            $this->db = $db;
        }
    }

    public function getFriendIdByUserId($userId){
        if(!$userId){
            return [];
        }
        $this->db->where("user_id", $userId);
        $this->db->where("status", 1);
        $column = 'friend_id as friendId';
        $info = $this->db->get($this->tableName,NULL,$column);
        if(!$info){
            return [];
        }
        return array_column($info, 'friendId');
    }

    public function addFriend($applyId,$userId){
        if(!$userId || !$applyId){
            return 0;
        }
        $data = Array (
            'user_id'=>$applyId,
            'friend_id'=>$userId,
            'status'=>1,
        );
        $id = $this->db->insert($this->tableName,$data);
        if(!$id){
            return 0;
        }
        if(!$this->lock){
            $this->lock=TRUE;
            $this->addFriend($userId,$applyId);
        }
        return $id;
    }

    public function delFriend($applyId,$userId){
        if(!$userId || !$applyId){
            return [];
        }
        $this->db->where("user_id", $userId);
        $this->db->where("friend_id", $applyId);
        $data['status'] = -1;
        $id = $this->db->update($this->tableName,$data);
        if(!$id){
            return [];
        }
        if(!$this->lock){
            $this->lock=TRUE;
            $this->delFriend($userId,$applyId);
        }
        return $id;
    }
}
